<template>
  <div class="warp-box clearfix">
    <div class="warp-con">
      <div class="header">
        <div class="headerWrapper">
          <div class="search">
            <el-form :inline="true">
              <el-form-item>
                <el-input placeholder="种质名称" v-model="query.name" clearable />
              </el-form-item>
              <el-form-item>
                <el-date-picker v-model="query.time" type="daterange" :default-time="['00:00:00', '23:59:59']"
                                start-placeholder="育苗时间" range-separator="至" end-placeholder="育苗时间"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="primary" @click="add" v-if="addBtn">新增</el-button>
                <el-dropdown @command="exportTmpVal" class="exportMenu" trigger="click" v-if="exportBtn">
                  <el-button type="primary">
                    导出<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown" style="background-color: rgb(21 120 176)">
                    <el-dropdown-item :command="false">
                      选择
                    </el-dropdown-item>
                    <el-dropdown-item :command="true">
                      全部
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="content">
        <el-table ref="multipleTable" border stripe v-loading="loading" :data="tableData" lement-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                  @select="handleSelect" @select-all="handleSelectAll" class="tableLine" :max-height="635">
          <el-table-column align="center" type="selection" v-if="exportBtn" />
          <el-table-column show-overflow-tooltip align="center" prop="name" label="种质名称" />
          <el-table-column show-overflow-tooltip align="center" prop="site" label="育苗地点" />
          <el-table-column align="center" prop="time" label="育苗时间" :formatter="dateFormat" :width="150" />
          <el-table-column show-overflow-tooltip align="center" prop="age" label="苗龄" :width="100" />
          <el-table-column show-overflow-tooltip align="center" prop="number" label="育苗数量" :width="100" />
          <el-table-column show-overflow-tooltip align="center" prop="quantity" label="现存数量" :width="100" />
          <el-table-column align="center" label="操作" :min-width="100">
            <template slot-scope="scope">
              <span @click="showDetail(scope.row)" class="pointer">查看</span>
              <span @click="showSeedlingSizes(scope.row)" class="pointer" v-if="sizesBtn"><i class="line"></i>出圃</span>
              <span @click="showSource(scope.row)" class="pointer"><i class="line"></i>溯源</span>
              <span @click="initCode(scope.row)" class="pointer" v-if="codeBtn"><i class="line"></i>扫码</span>
              <span @click="update(scope.row)" class="pointer" v-if="updateBtn"><i class="line"></i>修改</span>
              <span @click="remove(scope.row)" class="pointer" v-if="deleteBtn"><i class="line"></i>删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-sizes="[10,20,50]" :page-size="pageSize" :total="totalCount" @current-change="pager"
                       @size-change="handleSizeChange" background layout="total, sizes, prev, pager, next, jumper"/>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="dataVisible" :before-close="cancel" :close-on-click-modal="false">
      <el-form :model="dataForm" ref="ruleForm" class="demo-ruleForm">
        <div class="form-table">
          <table width="100%">
            <tr>
              <td class="form-item_label">种质名称</td>
              <td>
                <el-input class="td-input" v-model="dataForm.name" @focus="showRegister" :disabled="operation!==1"/>
              </td>
              <td>种名</td>
              <td>
                <el-input class="td-input" v-model="dataForm.specificName" disabled/>
              </td>
            </tr>
            <tr>
              <td class="form-item_label">育苗时间</td>
              <td>
                <el-date-picker v-model="dataForm.time" placeholder="选择日期" :disabled="operation===3"
                                type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"/>
              </td>
              <td>苗龄</td>
              <td>
                <el-input-number v-model="dataForm.age" :precision="0" :disabled="operation===3"/>
              </td>
            </tr>
            <tr>
              <td>育苗数量</td>
              <td>
                <el-input-number v-model="dataForm.number" @change="changeNumber" :precision="0"
                                 :min="minQuantity" :disabled="operation===3"/>
              </td>
              <td>现存数量</td>
              <td>
                <el-input class="td-input" v-model="dataForm.quantity" disabled/>
              </td>
            </tr>
            <tr>
              <td>育苗地点</td>
              <td>
                <el-input class="td-input" v-model="dataForm.site" :disabled="operation===3"/>
              </td>
              <td>苗木类型</td>
              <td>
                <el-select v-model="dataForm.type" clearable :disabled="operation===3">
                  <el-option v-for="(item, i) in type" :key="i" :label="item" :value="item"/>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>是否含有轻基质</td>
              <td>
                <el-select v-model="dataForm.lightMatrix" clearable :disabled="operation===3">
                  <el-option v-for="(item, i) in lightMatrix" :key="i" :label="item" :value="item"/>
                </el-select>
              </td>
              <td>容器规格</td>
              <td>
                <el-select v-model="dataForm.containerSize" clearable :disabled="operation===3">
                  <el-option v-for="(item, i) in containerSize" :key="i" :label="item" :value="item"/>
                </el-select>
              </td>
            </tr>
            <tr>
              <td>负责人</td>
              <td>
                <el-input class="td-input" v-model="dataForm.principal" :disabled="operation===3"/>
              </td>
              <td>联系电话</td>
              <td>
                <el-input class="td-input" v-model="dataForm.phone" :disabled="operation===3"/>
              </td>
            </tr>
            <tr>
              <td style="display:table-cell;vertical-align: middle">备注</td>
              <td colspan="3">
                <el-input type="textarea" v-model="dataForm.remark" :disabled="operation===3"/>
              </td>
            </tr>
          </table>
          <div style="margin-top: 20px">
            <el-form-item label="图片上传:">
              <el-upload action="#" list-type="picture-card" :file-list="fileList" :auto-upload="false"
                         :on-change="handleChange" :accept="'image/*'" :disabled="operation===3">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" style="min-height: 146px"/>
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="operation!==3" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <div class="preview">
                <el-dialog title="预览" :visible.sync="dialogVisible" :modal="false" width="1200px" top="50px">
                  <img :src="dialogImageUrl" alt=""/>
                </el-dialog>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="operation!==3" type="primary" @click="saveAdd" class="dialogBtn">保 存</el-button>
        <el-button type="primary" @click="cancel" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择种质" :visible.sync="registerVisible" :before-close="cancelRegister" :close-on-click-modal="false">
      <el-tabs v-model="activeTabs" tab-position="left" type="border-card" stretch @tab-click="handleClick">
        <el-tab-pane label="采集登记" name="gather">
          <el-form :inline="true" class="demo-form-inline" style="text-align: center;">
            <el-form-item>
              <el-input placeholder="种质名称" v-model="gatherQuery.grName" class="p-frame" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="upload" @click="queryGather">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table border stripe v-loading="registerLoading" :data="gatherTable" @row-click="checkedTableRows">
            <el-table-column show-overflow-tooltip align="center" prop="grName" label="种质名称" />
            <el-table-column show-overflow-tooltip align="center" prop="speName" label="种名"  />
            <el-table-column show-overflow-tooltip align="center" prop="speLaName" label="种拉丁名" />
            <el-table-column show-overflow-tooltip align="center" prop="source" label="种质来源" />
            <el-table-column show-overflow-tooltip align="center" prop="sourceType" label="种质来源类型" />
          </el-table>
          <div class="paging">
            <el-pagination :page-size="gatherQuery.pageSize" :current-page="gatherQuery.pageIndex" background
                           @current-change="gatherPager" :total="gatherCount" layout="total, prev, pager, next, jumper"/>
          </div>
        </el-tab-pane>
        <el-tab-pane label="保存登记" name="save">
          <el-form :inline="true" class="demo-form-inline" style="text-align: center;">
            <el-form-item>
              <el-input placeholder="种质名称" v-model="saveQuery.name" class="p-frame" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="upload" @click="querySave">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table border stripe v-loading="registerLoading" :data="saveTable" @row-click="checkedTableRows">
            <el-table-column show-overflow-tooltip align="center" prop="name" label="种质名称" />
            <el-table-column show-overflow-tooltip align="center" prop="speciesName" label="种名" />
            <el-table-column show-overflow-tooltip align="center" prop="speciesLdName" label="种拉丁名" />
            <el-table-column show-overflow-tooltip align="center" prop="amount" label="植株数量" />
            <el-table-column show-overflow-tooltip align="center" prop="growthEvaluation" label="生长性状" />
            <el-table-column show-overflow-tooltip align="center" prop="economicEvaluation" label="经济性状" />
          </el-table>
          <div class="paging">
            <el-pagination :page-size="saveQuery.pageSize" :current-page="saveQuery.pageIndex" background
                           @current-change="savePager" :total="saveCount" layout="total, prev, pager, next, jumper" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelRegister" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog width="540px" title="扫码查看详情" :close-on-click-modal="false" :visible.sync="qrCodeVisible">
      <div style="margin: 0 auto; text-align: center;">
        <canvas id="QRCode" style="margin: 0 auto" ref="qrCodeDiv" />
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="qrCodeVisible = false" class="dialogBtn" type="primary">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="sourceTitle" :visible.sync="sourceVisible" :before-close="cancelSource" :close-on-click-modal="false">
      <div class="form-table_source">
        <table width="100%" v-if="sourceType==='gather'">
          <tr>
            <td>种质名称</td>
            <td colspan="3">{{source.grName}}</td>
          </tr>
          <tr>
            <td>原编号</td>
            <td>{{source.originalNo}}</td>
            <td>种质来源</td>
            <td>{{source.source}}</td>
          </tr>
          <tr>
            <td>种名</td>
            <td>{{source.speName}}</td>
            <td>拉丁名</td>
            <td class="oblique">{{source.speLaName}}</td>
          </tr>
          <tr>
            <td>生活型</td>
            <td>{{source.lifeStyle}}</td>
            <td>常绿性</td>
            <td>{{source.evergreen}}</td>
          </tr>
          <tr>
            <td>种质来源类型</td>
            <td>{{source.sourceType}}</td>
            <td>主要特性</td>
            <td>{{source.feaMain}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              特异性特征
            </td>
            <td colspan="3">{{source.feaSpec}}</td>
          </tr>
          <tr>
            <td>用途</td>
            <td>{{source.purpose}}</td>
            <td style="display: table-cell; vertical-align: middle">
              种质来源地
            </td>
            <td>{{source.grSource}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              原产地备注
            </td>
            <td colspan="3">{{source.remarksCo}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              种质来源地备注
            </td>
            <td colspan="3">{{source.remarksSt}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              林分面积
            </td>
            <td>{{source.standArea}}</td>
            <td style="display: table-cell; vertical-align: middle">林龄</td>
            <td>{{source.forestAge}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">林相</td>
            <td colspan="3">{{source.forestApp}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              采集点联系人
            </td>
            <td>{{source.coContacts}}</td>
            <td style="display: table-cell; vertical-align: middle">
              采集点联系电话
            </td>
            <td>{{source.coPhone}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              采集人
            </td>
            <td>{{source.collector}}</td>
            <td style="display: table-cell; vertical-align: middle">
              采集时间
            </td>
            <td>{{source.coTime}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              登记人员
            </td>
            <td colspan="3">{{source.regPer}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              登记单位
            </td>
            <td style="text-indent: 0px;">
              <SelectTree :options="unit" :value="source.regUnit" disabled />
            <td style="display: table-cell; vertical-align: middle">
              登记时间
            </td>
            <td>{{source.regTime}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">经度</td>
            <td>{{source.lon}}</td>
            <td style="display: table-cell; vertical-align: middle">纬度</td>
            <td>{{source.lat}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">高度</td>
            <td>{{source.alt}}</td>
            <td style="display: table-cell; vertical-align: middle">坡位</td>
            <td>{{source.slPos}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">坡向</td>
            <td>{{source.aspect}}</td>
            <td style="display: table-cell; vertical-align: middle">坡度</td>
            <td>{{source.slope}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">
              土壤类型
            </td>
            <td>{{source.soilType}}</td>
            <td style="display: table-cell; vertical-align: middle">
              立地条件
            </td>
            <td>{{source.siteCond}}</td>
          </tr>
          <tr>
            <td style="display: table-cell; vertical-align: middle">备注</td>
            <td colspan="3">{{source.remarks}}</td>
          </tr>
        </table>
        <table width="100%" v-else>
          <tr>
            <td>种质名称</td>
            <td>{{source.name}}</td>
            <td>库中编号</td>
            <td>{{source.code}}</td>
          </tr>
          <tr>
            <td>种名</td>
            <td>{{source.speciesName}}</td>
            <td>种拉丁名</td>
            <td class="oblique">{{source.speciesLdName}}</td>
          </tr>
          <tr>
            <td>保存库</td>
            <td>{{resource[source.oneId]}}</td>
            <td>保存区</td>
            <td>{{resource[source.twoId]}}</td>
          </tr>
          <tr>
            <td>树种分区</td>
            <td>{{resource[source.threeId]}}</td>
            <td>小区</td>
            <td>{{resource[source.fourId]}}</td>
          </tr>
          <tr>
            <td>保存种质</td>
            <td>{{source.germplasm}}</td>
            <td>种质类型</td>
            <td>{{source.type}}</td>
          </tr>
          <tr>
            <td>种质来源地</td>
            <td>{{source.source}}</td>
            <td>保存材料来源类型</td>
            <td>{{source.materials}}</td>
          </tr>
          <tr>
            <td>调查分类</td>
            <td>{{template[source.templateId]}}</td>
            <td>育苗时间</td>
            <td>{{source.seedlingTime}}</td>
          </tr>
          <tr>
            <td>保存时间</td>
            <td>{{source.saveTime}}
            </td>
            <td>植株数量</td>
            <td>{{source.amount}}</td>
          </tr>
          <tr>
            <td>种植密度</td>
            <td>{{source.density}}</td>
            <td>库中位置</td>
            <td>{{source.lon}} {{source.lat}} {{source.alt}}</td>
          </tr>
          <tr>
            <td>生长性状评价</td>
            <td>{{source.growthEvaluation}}</td>
            <td>经济性状评价</td>
            <td>{{source.economicEvaluation}}</td>
          </tr>
          <tr>
            <td>具体用途</td>
            <td colspan="3">{{source.purpose}}</td>
          </tr>
          <tr>
            <td>生长习性</td>
            <td colspan="3">{{source.habit}}</td>
          </tr>
          <tr>
            <td>开花结实习性</td>
            <td colspan="3">{{source.hsHabit}}</td>
          </tr>
          <tr>
            <td>收集单位</td>
            <td style="text-indent: 0px">
              <SelectTree :options="unit" :value="source.collectUnit" disabled />
            </td>
            <td>登记单位</td>
            <td style="text-indent: 0px">
              <SelectTree :options="unit" :value="source.registerUnit" disabled />
            </td>
          </tr>
          <tr>
            <td>登记时间</td>
            <td>{{source.registerTime}}</td>
            <td>登记人员</td>
            <td>{{source.registrant}}</td>
          </tr>
          <tr>
            <td>联系方式</td>
            <td colspan="3">{{source.registrantPhone}}</td>
          </tr>
          <tr>
            <td>备注</td>
            <td colspan="3">{{source.remark}}</td>
          </tr>
        </table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelSource" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="出圃" :visible.sync="seedlingSizesVisible" :before-close="cancelSeedlingSizes" :close-on-click-modal="false">
      <div class="form-table">
        <table width="100%">
          <tr>
            <td class="form-item_label">种质名称</td>
            <td>
              <el-input class="td-input" v-model="seedlingSizes.name" disabled />
            </td>
            <td>育苗时间</td>
            <td>
              <el-date-picker disabled v-model="seedlingSizes.time" type="date"
                              format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"/>
            </td>
          </tr>
          <tr>
            <td>联系人</td>
            <td><el-input class="td-input" v-model="seedlingSizes.contact" /></td>
            <td>种植区县</td>
            <td><el-input class="td-input" v-model="seedlingSizes.plantLocation" /></td>
          </tr>
          <tr>
            <td class="form-item_label">数量</td>
            <td><el-input-number v-model="seedlingSizes.quantity" :precision="0" :min="0" :max="maxQuantity"/></td>
            <td>种植目的</td>
            <td><el-input class="td-input" v-model="seedlingSizes.purpose" /></td>
          </tr>
          <tr>
            <td style="display:table-cell;vertical-align:middle">其他情况说明</td>
            <td colspan="3">
              <el-input type="textarea" maxlength="300" show-word-limit v-model="seedlingSizes.explain" />
            </td>
          </tr>
        </table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSeedlingSizes" class="dialogBtn">保 存</el-button>
        <el-button type="primary" @click="cancelSeedlingSizes" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment'
import QRCode from 'qrcode'
import resourceApi from '@/api/resourceApi'
import systemApi from "../../../api/systemApi";
import SelectTree from '@/components/TreeSelect'
import ResourceManageApi from "../../../api/ResourceManageApi";
import seedlingSizesApi from "../../../api/seedlingSizesApi";
import seedlingBreedingApi from "../../../api/seedlingBreedingApi";
import templateApi from "../../../api/templateApi";

export default {
  name: 'seedlingBreeding',
  components: {
    SelectTree
  },
  data() {
    return {
      query: {},
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      tableData: [],
      loading: false,
      title: null,
      dataForm: {},
      fileList: [],
      fileAll: [],
      dialogVisible: false,
      dialogImageUrl: '',
      operation: null,
      dataVisible:false,
      type: ['种子', '扦插', '麦苗砧嫁接', '小苗嫁接', '组培', '其他'],
      lightMatrix: ['是', '否'],
      containerSize: ['小杯', '大杯'],
      activeTabs: null,
      registerVisible: false,
      registerLoading: false,
      gatherQuery: {
        grName: null,
        pageIndex: 1,
        pageSize: 5
      },
      gatherCount: 0,
      gatherTable: [],
      saveQuery: {
        name: null,
        pageIndex: 1,
        pageSize: 5
      },
      saveCount: 0,
      saveTable: [],
      qrCodeVisible: false,
      source: {},
      sourceType: null,
      sourceTitle: null,
      sourceVisible: false,
      unit: [],
      resource: {},
      template: {},
      purpose: ['试验用苗', '生产用苗'],
      minQuantity: 0,
      maxQuantity: 0,
      seedlingSizes: {},
      seedlingSizesVisible: false,
      number: 0,
      tableRow: {},
      addBtn: false,
      sizesBtn: false,
      codeBtn: false,
      updateBtn: false,
      deleteBtn: false,
      exportBtn: false,
      onlyId: [],
      FILE_SERVER: process.env.FILE_SERVER
    }
  },
  created() {
    this.initBtn()
    this.findPage()
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList.push(file);
      if(!((file.raw.type === 'image/png' || file.raw.type === 'image/gif' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/PNG' || file.raw.type === 'image/JPG' || file.raw.type === 'image/JPEG'))){
        this.handleRemove(file);
        this.$message({
          message: '只能上传图片文件',
          type: 'warning'
        });
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      if (file.id) {
        this.$confirm('确定删除该附件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resourceApi.delGatherPic(file.id).then((res) => {
            if (res.data.messageCode === '200') {
              this.$notify({
                title: '消息',
                message: '删除成功！',
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              for (let i in this.fileList) {
                let item = this.fileList[i]
                if (item.id === file.id) {
                  this.fileList.splice(i, 1)
                  break
                }
              }
            }
          })
        })
      } else {
        this.fileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.fileList.splice(index, 1)
          }
        })
      }
    },
    search() {
      this.pageIndex = 1;
      this.clearSelection();
      this.findPage();
    },
    findPage() {
      this.loading = true
      let params = {
        name: this.query.name,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
        startTime: this.query.time ? this.query.time[0] : null,
        endTime: this.query.time ? this.query.time[1] : null
      }
      seedlingBreedingApi.findPage(params).then(res => {
        this.loading = false
        let result = res.data.result
        if (res.data.message === 'success' && result) {
          this.totalCount = result.totalCount
          this.tableData = result.rows

          let onlyId = this.onlyId
          if (onlyId.length > 0) {
            this.$nextTick(() => {
              this.tableData.forEach((row) => {
                for (let i in onlyId) {
                  let id = onlyId[i];
                  if (row.id === id) {
                    this.$refs.multipleTable.toggleRowSelection(row);
                    break;
                  }
                }
              });
            });
          }
        } else {
          this.totalCount = 0
          this.tableData = []
        }
      })
    },
    pager(val) {
      this.pageIndex = val
      this.findPage()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.findPage()
    },
    add() {
      this.title = "新增"
      this.operation = 1
      this.dataVisible = true
    },
    cancel() {
      this.number = {}
      this.dataForm = {}
      this.fileList = []
      this.minQuantity = 0
      this.dataVisible = false
    },
    showRegister() {
      this.activeTabs = 'gather'
      this.findGather()
      this.registerVisible = true
    },
    handleClick(tab, event) {
      let name = tab.name
      if (name === 'gather') {
        this.findGather()
      } else {
        this.findSave()
      }
    },
    cancelRegister() {
      this.initGather()
      this.initSave()
      this.registerVisible = false
    },
    initGather() {
      this.gatherQuery = {
        grName: null,
        pageIndex: 1,
        pageSize: 8
      }
      this.gatherCount = 0
      this.gatherTable = []
    },
    initSave() {
      this.saveQuery = {
        name: null,
        pageIndex: 1,
        pageSize: 5
      }
      this.saveCount = 0
      this.saveTable = []
    },
    queryGather() {
      this.gatherQuery.pageIndex = 1;
      this.findGather();
    },
    findGather() {
      this.registerLoading = true
      resourceApi.findRegisterGatherPage(this.gatherQuery).then(res => {
        this.registerLoading = false
        if (res.data.message === 'success' && res.data.result) {
          this.gatherTable = res.data.result.rows
          this.gatherCount = res.data.result.totalCount
        } else {
          this.gatherTable = []
          this.gatherCount = 0
        }
      })
    },
    gatherPager(val) {
      this.gatherQuery.pageIndex = val
      this.findGather()
    },
    querySave() {
      this.saveQuery.pageIndex = 1;
      this.findSave();
    },
    findSave() {
      this.registerLoading = true
      resourceApi.findRegisterPreservationPage(this.saveQuery).then(res => {
        this.registerLoading = false
        if (res.data.message === 'success' && res.data.result) {
          this.saveTable = res.data.result.rows
          this.saveCount = res.data.result.totalCount
        } else {
          this.saveTable = []
          this.saveCount = 0
        }
      })
    },
    savePager(val) {
      this.saveQuery.pageIndex = val
      this.findSave()
    },
    checkedTableRows(row, column, event) {
      let active = this.activeTabs
      this.dataForm.gatherId = null
      this.dataForm.saveId = null
      if (active === 'gather') {
        this.dataForm.gatherId = row.id
        this.$set(this.dataForm, 'name', row.grName)
        this.$set(this.dataForm, 'specificName', row.speName)
      } else {
        this.dataForm.saveId = row.id
        this.$set(this.dataForm, 'name', row.name)
        this.$set(this.dataForm, 'specificName', row.speciesName)
      }
      this.cancelRegister()
    },
    saveAdd() {

      let name = this.dataForm.name
      if (!name || name.length < 1) {
        this.$message({
          message: '种质名称不能为空',
          type: 'warning'
        })
        return false
      }
      let time = this.dataForm.time
      if (!time) {
        this.$message({
          message: '育苗时间不能为空',
          type: 'warning'
        })
        return false
      }
      let text= delete this.dataForm.fileList
      seedlingBreedingApi.save(this.fromData(this.dataForm)).then(res => {
        if (res.data.message === 'success') {
          this.$notify({
            title: '消息',
            message: ('保存成功！'),
            position: 'bottom-right',
            showClose: false,
            type: 'success'
          })
          this.findPage()
          this.cancel()
        }
      })
    },
    fromData(form) {
      let formData = new FormData();
      for (let item of this.fileList) {
        if (item.raw) {
          formData.append("accessory", item.raw);
        }
      }
      for (let key in form) {
        if (form[key] == null || form[key] === "null") {
          form[key] = "";
        }
        formData.append(key, form[key]);
      }
      return formData;
    },
    update(row) {
      this.title = '修改'
      this.operation = 2
      seedlingBreedingApi.getInfo(row).then(res => {
        if (res.data.message === 'success') {
          this.dataForm = res.data.result
          let quantity = this.dataForm.quantity
          this.number = this.dataForm.number
          this.minQuantity = quantity === 0 ? this.number : this.number - quantity
          this.dataForm.fileList.forEach((item) => {
            item.url = this.FILE_SERVER + item.path
            this.fileList.push(item)
          })
          this.dataVisible = true
        }
      })
    },
    showDetail(row) {
      this.title = '查看'
      this.operation = 3
      seedlingBreedingApi.getInfo(row).then(res => {
        if (res.data.message === 'success') {
          this.dataForm = res.data.result
          this.dataForm.fileList.forEach((item) => {
            item.url = this.FILE_SERVER + item.path
            this.fileList.push(item)
          })
          this.dataVisible = true
        }
      })
    },
    dateFormat(row,column){
      let date = row[column.property];
      if(date == undefined){return ''};
      return moment(date).format("YYYY-MM-DD")
    },
    remove(row) {
      let tips = ''
      if (row) {
        tips = `此操作将删除: ${row.name}, 是否继续?`
      } else {
        return false
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seedlingBreedingApi.remove(row).then(res => {
          if (res.data.message === 'success') {
            this.findPage()
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
          }
        })
      }).catch(() => {})
    },
    initCode(row) {
      this.qrCodeVisible = true
      this.$nextTick(() => {
        this.$refs.qrCodeDiv.innerHTML = ''
        let curl = row.id.toUpperCase()
        QRCode.toCanvas(this.$refs.qrCodeDiv, curl, {
          width: 300,
          height: 300,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff' // 二维码背景色
        }, function(error) {
          if (error) console.error(error)
        })
      })
    },
    showSource(row) {
      let result = null
      let gatherId = row.gatherId
      if (gatherId) {
        this.sourceType = 'gather'
        this.sourceTitle = '查看采集登记'
        result = this.getGather(gatherId)
      } else {
        this.sourceType = 'save'
        this.sourceTitle = '查看保存登记'
        this.findTemplate()
        this.findResourceManage()
        result = this.getSave(row.saveId)
      }
      if (result) {
        this.findUnit()
        result.then(res => {
          if (res.data.message === 'success') {
            this.source = res.data.result
            this.sourceVisible = true
          }
        })
      }
    },
    async getGather(id) {
      return await resourceApi.getRegisterGatherInfo(id)
    },
    async getSave(id) {
      return await resourceApi.getRegisterPreservationInfo(id)
    },
    cancelSource() {
      this.source = {}
      this.sourceType = null
      this.sourceVisible = false
    },
    findUnit() {
      systemApi.getDeparmentList().then((res) => {
        if (res.data.message === 'success') {
          this.unit = res.data.result
        } else {
          this.unit = []
        }
      })
    },
    findResourceManage() {
      this.resource = {}
      ResourceManageApi.findList().then(res => {
        if (res.data.message === 'success') {
          let result = res.data.result
          if (result) {
            result.forEach(item => {
              this.$set(this.resource, item.id, item.name)
            })
          }
        }
      })
    },
    findTemplate() {
      templateApi.findTemplate('TEMPLATE').then(res => {
        if (res.data.message === 'success') {
          let result = res.data.result
          if (result) {
            result.forEach(item => {
              this.$set(this.template, item.id, item.name)
            })
          }
        } else {
          this.template = {}
        }
      })
    },
    showSeedlingSizes(row) {
      seedlingBreedingApi.getInfo(row).then(res => {
        if (res.data.message === 'success') {
          let data = res.data.result
          this.tableRow = data
          this.maxQuantity = data.quantity
          this.$set(this.seedlingSizes, 'name', data.name)
          this.$set(this.seedlingSizes, 'time', data.time)
          this.$set(this.seedlingSizes, 'breedingId', data.id)
          this.seedlingSizesVisible = true
        }
      })
    },
    cancelSeedlingSizes() {
      this.fileList = [];
      this.tableRow = {}
      this.maxQuantity = 0
      this.seedlingSizes = {}
      this.seedlingSizesVisible = false
    },
    saveSeedlingSizes() {
      let quantity = this.seedlingSizes.quantity
      if (!quantity) {
        this.$message({
          message: '出圃数量不能为空',
          type: 'warning'
        })
        return false
      }

      seedlingSizesApi.save(this.fromData(this.seedlingSizes)).then(res => {
        if (res.data.message === 'success') {
          this.$notify({
            title: '消息',
            message: ('保存成功！'),
            position: 'bottom-right',
            showClose: false,
            type: 'success'
          })
          this.cancelSeedlingSizes()
        } else {
          this.seedlingSizes.quantity = 0
          this.showSeedlingSizes(this.tableRow)
        }
        this.findPage()
      })
    },
    changeNumber(val) {
      if (this.operation === 1) {
        this.dataForm.quantity = val
      } else {
        if (val === this.number) {
          this.dataForm.quantity = this.number - this.minQuantity
        } else {
          this.dataForm.quantity = val - this.minQuantity
        }
      }
    },
    initBtn() {
      let permissionBtn = JSON.parse(localStorage.permissionBtn)
      this.addBtn = permissionBtn['seedling_breeding_add']
      this.sizesBtn = permissionBtn['seedling_breeding_sizes']
      this.codeBtn = permissionBtn['seedling_breeding_code']
      this.updateBtn = permissionBtn['seedling_breeding_update']
      this.deleteBtn = permissionBtn['seedling_breeding_delete']
      this.exportBtn = permissionBtn['seedling_breeding_export']
    },
    handleSelect(selection, row) {
      let id = row.id;
      let checked = false;
      for (let i in selection) {
        let item = selection[i];
        if (item.id === id) {
          checked = true;
          break;
        }
      }
      if (checked) {
        this.onlyId.push(id);
      } else {
        let index = this.onlyId.indexOf(id)
        this.onlyId.splice(index, 1);
      }
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        for (let i in selection) {
          let item = selection[i]
          if (this.onlyId.indexOf(item.id) === -1) {
            this.onlyId.push(item.id)
          }
        }
      } else {
        let data = this.tableData
        for (let i in data) {
          let item = data[i]
          let index = this.onlyId.indexOf(item.id)
          if (index !== -1) {
            this.onlyId.splice(index, 1)
          }
        }
      }
    },
    clearSelection() {
      this.onlyId = []
      this.$refs.multipleTable.clearSelection()
    },
    async exportTmpVal(isAll) {
      if (!isAll) {
        if (this.onlyId.length === 0) {
          this.$message({
            message: "请选择需要导出的数据",
            type: "warning",
          });
          return false;
        }
      }

      let loading = this.$loading({
        lock: true,
        text: '数据导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      let time = this.query.time
      let params = {
        isAll: isAll,
        onlyId: this.onlyId,
        start: time ? time[0] : null,
        end: time ? time[1] : null,
        name: this.query.name
      }
      let url = '/gr/seedlingBreeding/exportExcel'
      await resourceApi.downloadExcel(url, params)
      loading.close()
      this.clearSelection()
    }
  }
}
</script>
<style lang="less" scoped>
.search {
  & /deep/ .el-form-item__label {
    font-size: 1.8rem;
  }
}

.form-table {
  width: 100%;

  table,
  tr,
  td {
    border: 1px solid #fff;
  }

  td {
    &:nth-child(even) {
      width: 32%;
    }

    &:nth-child(odd) {
      text-indent: 10px;
    }
  }

  /deep/ .el-input__inner {
    border: none;
  }
  /deep/ .el-textarea__inner {
    border: none;
  }
}

.el-form-item__label {
  padding: 0 20px 0 0 !important;
}

.footer {
  margin-top: 40px;
  color: #ffffff;
  font-size: 16px;

  .info {
    .select {
      width: 52px;
      height: 35px;
    }

    .select /deep/ .el-input__inner {
      padding-left: 5px;
      padding-right: 0;
    }

    .select /deep/ .el-input__icon {
      width: 15px;
    }

    .select /deep/ .el-select__caret {
      /*transform:rotate(270deg);*/
      /*color: black;*/
    }

    .select /deep/ .el-select__caret.is-reverse {}
  }
}

.content {
  margin-top: 10px;

  & /deep/ .el-checkbox__inner {
    height: 20px;
    width: 20px;
    font-size: 28px;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    background: none;
  }

  & /deep/ .el-tooltip__popper {
    background-color: red;
  }

  & /deep/ .el-checkbox__inner::after {
    border-width: 2px;
    /* border-color: black; */
    height: 6px;
    left: 6px;
    top: 3px;
    width: 4px;
  }

  & /deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
    top: 8px;
    background: white;
  }
}

.line {
  display: inline-flex;
  height: 21px;
  width: 1px;
  background: rgba(0, 255, 255, 1);
  margin: 0 10px;
  vertical-align: middle;
}

.dialogBtn {
  font-size: 1.6rem;

  &:hover {
    background: rgba(12, 161, 151, 1);
  }
}

.coordinate {
  width: 25%;
}
.footer-paging {
  text-align: right;
  padding-right: 30px;

  & /deep/ .el-pagination.is-background .btn-prev {
    background: none;
    border: 1px solid rgba(0, 255, 255, 1);
  }

  & /deep/ .el-pagination.is-background .btn-next {
    background: none;
    border: 1px solid rgba(0, 255, 255, 1);
  }

  & /deep/ .el-pager li {
    background: none;
    border: 1px solid rgba(0, 255, 255, 1);
  }

  & /deep/ .el-pagination__total,
  & /deep/ .el-pagination__sizes {
    float: left;
    font-size: 1.6rem;
    height: 35px;
    line-height: 35px;
  }

  & /deep/ .el-input__inner {
    height: 35px;
  }

  & /deep/ .el-input .el-input__inner {
    padding-right: 20px;
    color: #ffffff;
    font-size: 1.6rem;
  }

  .select {
    width: 52px;
    height: 35px;
  }

  .select /deep/ .el-input__inner {
    padding-left: 5px;
    padding-right: 0;
  }

  .select /deep/ .el-input__icon {
    width: 15px;
  }
}

#QRCode {
  display: flex;
  justify-content: center;
}

/deep/ .el-tabs--border-card {
  background: #031926;
}
.form-table_source {
  width: 100%;
  table,
  tr,
  td {
    text-indent: 10px;
    border: 1px solid #fff;
    font-size: 14px;
    line-height: 40px;
  }
  td {
    &:nth-child(even) {
      width: 32%;
    }
  }

  /deep/ .el-input__inner {
    border: none;
    background-color: #04293b;;
  }

  /deep/ .el-icon-arrow-up {
    display: none;
  }

  .oblique {
    font-style:oblique;
  }
}


.exportMenu {
  margin-left: 10px;
}

/deep/ .el-dropdown-menu__item:focus,
.el-dropdown-menu__item:not(.is-disabled):hover {
  color: #ffffff;
  background-color: #32f1ff16;
}
</style>
<style lang="less">
/**
   * 修改样式   覆盖默认的饿了么全局样式
   */
.el-form-item__label {
  padding: 0 20px 0 0 !important;
}
</style>
